package com.heisenhub.common.oauth.hander;

import com.heisnenhub.common.module.constant.HttpConstant;
import com.heisnenhub.common.module.utils.Api;
import com.heisnenhub.common.module.utils.ResponseUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
public class XmAuthExceptionEntryPoint implements AuthenticationEntryPoint {


    /**
     * 令牌不正确返回401
     * @param request that resulted in an <code>AuthenticationException</code>
     * @param response so that the user agent can begin authentication
     * @param authException that caused the invocation
     * @throws IOException
     */
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) throws IOException {
        Throwable cause = authException.getCause();
        String msg ;
        if (cause instanceof InvalidTokenException) {
            msg = HttpConstant.HttpMsg.MSG_INVALID_TOKEN;
        } else {
            msg = HttpConstant.HttpMsg.MSG_IDENTITY_AUTHENTICATION;
        }
        log.info("【  401  】 {}",msg);
        ResponseUtils.makeResponse(response,MediaType.APPLICATION_JSON_UTF8_VALUE,HttpServletResponse.SC_UNAUTHORIZED, Api.fail(msg));

    }
}
